import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getFuDiVenueSettings } from '../request.js';

/**
 * 3.5+网球（福地）场地数据处理器
 */
export class ThreePointFiveFuDiProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '3.5+网球（福地）';
  }

  /**
   * 获取3.5+网球（福地）场地预约设置
   * @param {Object} params - 查询参数 { date, deskTypeId, shopId, shopName, token }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const defaultParams = {
      date: "2025-09-02",
      deskTypeId: "463560331927552",
      shopId: "455834640958464",
      shopName: "3.5+网球运动馆",
      token: ""
    };
    
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getFuDiVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
  validateData(data) {
    const actualData = data.data || data;
    return actualData && 
           actualData.deskArr && 
           Array.isArray(actualData.deskArr) &&
           actualData.itemArr && 
           Array.isArray(actualData.itemArr);
  }

  /**
   * 按场地名称分组
   * @param {Object} data - 原始场地数据
   * @returns {Map} 场地Map
   */
  groupVenues(data) {
    const venueMap = new Map();
    const actualData = data.data || data;
    
    actualData.deskArr.forEach(desk => {
      const venueName = desk.deskName;
      if (!venueMap.has(venueName)) {
        venueMap.set(venueName, {
          name: venueName,
          deskId: desk.deskId,
          timeSlots: []
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间槽
   * @param {Map} venueMap - 场地Map
   * @param {Object} data - 原始场地数据
   */
  processTimeSlots(venueMap, data) {
    const actualData = data.data || data;
    
    venueMap.forEach((venue, venueName) => {
      // 查找对应的场地
      const desk = actualData.deskArr.find(d => d.deskName === venueName);
      if (!desk) return;
      
      // 遍历时间间隔信息
      actualData.itemArr.forEach(item => {
        if (item.deskId === desk.deskId) {
          const timeSlot = `${item.beginTime.substring(0, 5)}-${item.endTime.substring(0, 5)}`;
          const beginDatetime = `${this.selectedDate} ${item.beginTime}`;
          const endDatetime = `${this.selectedDate} ${item.endTime}`;
          
          // 检查场地状态
          const isLocked = item.status === 1; // 假设status=1表示已被预订
          
          // 添加时间槽信息
          venue.timeSlots.push({
            time: timeSlot,
            isFree: !isLocked,
            price: parseFloat(item.price) || 30,
            beginDatetime: beginDatetime,
            endDatetime: endDatetime
          });
        }
      });
    });
  }

  /**
   * 转换为场地列表
   * @param {Map} venueMap - 场地Map
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    return Array.from(venueMap.values()).map((venue, index) => {
      // 根据场地名称设置价格
      let price = 30; // 默认价格
      
      return {
        id: 21000 + index, // 给3.5+福地场地分配ID
        name: venue.name,
        address: "深圳市南山区西丽街道福地路",
        latitude: 22.6123,
        longitude: 113.9724,
        phone: '0769-33445566',
        rating: 4.5,
        price: price,
        facilities: ['室内场地', '专业教练'],
        image: '',
        distance: 4.5,
        timeSlots: venue.timeSlots,
        dataSource: this.venueName
      };
    });
  }

  /**
   * 处理场地数据
   * @param {Object} data - 原始场地数据
   * @param {string} selectedDate - 选择的日期
   * @returns {Array} 处理后的场地列表
   */
  process(data, selectedDate) {
    this.selectedDate = selectedDate;
    
    // 验证数据
    if (!this.validateData(data)) {
      console.error('3.5+福地数据验证失败');
      return [];
    }
    
    // 按场地名称分组
    const venueMap = this.groupVenues(data);
    
    // 处理时间槽
    this.processTimeSlots(venueMap, data);
    
    // 转换为场地列表
    return this.convertToVenueList(venueMap);
  }
}

export default ThreePointFiveFuDiProcessor;